//
//  CEIDataModel.m
//  Balance
//
//  Created by Calvin Kuo on 12-05-09.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

/*
 Status: changed
 Last Merge Date: 06-08-2012
 Last Change Date: 
 Changes:
 1. population of priorYearPercent
  
 */

#import "CEIDataModel.h"

@implementation CEIDataModel

@synthesize dailyCEI = _dailyCEI;
@synthesize allCEI = _allCEI;
@synthesize monthlyCEIKeys = _monthlyCEIKeys;


-(id) init{
    if (self = [super init]){
        
       //prepare data for the CEI plots, 3 years from today and back
              
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"yyyyMMdd"];
        NSDate * newYearDay2012 = [df dateFromString:@"20120101"];
        NSDate * today = [NSDate date];
        NSString *todayString = [df stringFromDate:today];
        NSString *startDateString = [@"2009" stringByAppendingString:[todayString substringWithRange:NSMakeRange(4,4)] ];
        NSDate *startDate = [df dateFromString:startDateString];
        NSDate *endOfYear2009=[df dateFromString:@"20091231"];
        
        NSUInteger daysin2012 = [self getNumberOfDaysFrom:newYearDay2012 to:today] +1;
        NSUInteger daysin2009 = [self getNumberOfDaysFrom:startDate to:endOfYear2009] +1;
        numberOfDays = daysin2009 + 365 + 365 + daysin2012;
        
        NSTimeInterval oneDayIntervals = 24 * 60 * 60;
       
        _dailyCEI = [NSMutableDictionary dictionaryWithCapacity:2000];
        _allCEI = [NSMutableDictionary dictionaryWithCapacity:2000];
               
        for (int d=0; d < numberOfDays; d++){
            
            //CEIData *data = [[CEIData alloc] init];
            NSDate *ceiDate = [today dateByAddingTimeInterval:(oneDayIntervals * -d)]; 
            //data.ceiDate = ceiDate;
            //data.timeIntervalSinceToday = oneDayIntervals * d;
            //data.timeIntervalSinceStart = oneDayIntervals * (numberOfDays-d-1);
            NSString *stringFromCEIDate = [df stringFromDate:ceiDate];
            
            CEIData *oneCollector= [[CEIData alloc] init];
            CEIData *allCollectors= [[CEIData alloc] init];
            oneCollector.ceiDate = ceiDate;
            allCollectors.ceiDate = ceiDate;
            oneCollector.timeIntervalSinceToday =  oneDayIntervals * d;
            allCollectors.timeIntervalSinceToday = oneDayIntervals * d;
            
            oneCollector.timeIntervalSinceStart = oneDayIntervals * (numberOfDays-d-1);  
            allCollectors.timeIntervalSinceStart = oneDayIntervals * (numberOfDays-d-1);   
            
            int ran = (arc4random()%100) * 0.02;
            int n = 250; //curve every 400 points
            int t = d - (n*(d/n)); //401 => 1
            int q = ((t%n)<(n/2) ? (t%n) : ((t%n)-((t-(n/2))*2))); // 200 <= 198; 201 <= 197
            float p = 75 + ran + q*0.1 - d*0.04;
            oneCollector.ceiPercent = [NSNumber numberWithFloat:p];
            
            ran = (arc4random()%100) * 0.02;
            n = 600; //curve every 600 points
            t = d - (n*(d/n)); //401 => 1
            q = ((t%n)<(n/2) ? (t%n) : ((t%n)-((t-(n/2))*2))); // 200 <= 198; 201 <= 197
            p = 75 + ran + q*0.05 - d*0.02;
            allCollectors.ceiPercent = [NSNumber numberWithFloat:p];
            
                       
            [_dailyCEI setObject:oneCollector forKey: stringFromCEIDate];
            [_allCEI setObject:allCollectors forKey: stringFromCEIDate];
            
        }
        
        
        
       
        NSArray *dailyCEIkeys = [_dailyCEI allKeys];
        NSArray *sortedKeys = [dailyCEIkeys sortedArrayUsingSelector:@selector(compare:)];

        
        //prepare priorYearPercent data
        for (int d = 0; d < [dailyCEIkeys count]; d++){
            if (d > 364){
                CEIData *currentData = [_dailyCEI objectForKey: [sortedKeys objectAtIndex:d]];
                CEIData *priorData = [_dailyCEI objectForKey: [sortedKeys objectAtIndex:(d-365)]];
                currentData.priorYearPercent = priorData.ceiPercent;
            } else {
                CEIData *currentData = [_dailyCEI objectForKey: [sortedKeys objectAtIndex:d]];
                currentData.priorYearPercent = [NSNumber numberWithInt:0];
            }
            
            //[_dailyCEI removeObjectForKey:[sortedKeys objectAtIndex:d]];
            //[_dailyCEI setObject:currentData forKey:[sortedKeys objectAtIndex:d]];
    
        }
                 
         //prepare data for the slider plot
        NSMutableArray *selectedDailyKeys = [NSMutableArray arrayWithCapacity:500]; 
  
           
        /*for (int s=0; s < [dailyCEIkeys count]; s++) {
            NSString *dd = [[sortedKeys objectAtIndex:s] substringFromIndex:6];
            if ([dd isEqualToString: @"01"] || [dd isEqualToString: @"15"])
                [selectedDailyKeys addObject: [sortedKeys objectAtIndex:s]];
        };*/
        
        CEIData *firsDayData = [_dailyCEI objectForKey:[sortedKeys objectAtIndex:0]];
        int firstDayInterval = firsDayData.timeIntervalSinceStart;
        //NSLog(@"firstDayInterval = %i",firstDayInterval);
        for (int s=0; s < [sortedKeys count]; s++) {
            CEIData *data = [_dailyCEI objectForKey:[sortedKeys objectAtIndex:s]];
                        int dataInterval = data.timeIntervalSinceStart - firstDayInterval;
            //NSLog(@"s=%i, date: %@",s, [sortedKeys objectAtIndex:s]);
            if ( dataInterval % (60 * 60 * 24 * 15) == 0 ){
                [selectedDailyKeys addObject: [sortedKeys objectAtIndex:s]];
                //NSLog(@"date added to slider: %@",[sortedKeys objectAtIndex:s]);
            }
        };
        //NSLog(@"count = %i",[selectedDailyKeys count]);

        

       _monthlyCEIKeys = [NSArray arrayWithArray:selectedDailyKeys];
    
       
    }
    return self;
}

/*
-(NSUInteger)getNumberOfDaysThisYearTillToday
{
    NSDateFormatter *df = [[NSDateFormatter alloc]init];  
    [df setDateFormat:@"MM-dd-yyyy"];  
    
    NSDate * newYearDay = [df dateFromString:@"01-01-2012"]; 
    NSDate * today = [[NSDate alloc]init];
    
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    
    //to get number of days since 01-01-2012
    NSDateComponents *components = [gregorian components:NSDayCalendarUnit
                                                fromDate:newYearDay
                                                  toDate:today options:0];
    
    NSInteger days = [components day];
    
    return days;
    //NSLog(@"days = %d", days);
    
}*/

-(NSUInteger)getNumberOfDaysFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [gregorian components:NSDayCalendarUnit
                                                fromDate:fromDate
                                                  toDate:toDate options:0];
    
    NSInteger days = [components day];
    
    return days;
    
}



@end
